#include "stdafx.h"
#include "ChessTrainerWrapper.h"

#include "FiveWinnerChecker.h"

#include "../Strategy/ChessTree.h"

using namespace System;
using namespace System::Runtime::InteropServices;

namespace UnManagedWrapper
{
	ChessTrainerWrapper::ChessTrainerWrapper(FiveInRow::ITrainer^ trainer) :
		_trainer(trainer)
	{
		_tree = (new ChessTree(new FiveWinnerChecker(_trainer->ChessSize)));
	}

	ChessTrainerWrapper::ChessTrainerWrapper(String^ treePath, FiveInRow::ITrainer^ trainer) :
		_trainer(trainer)
	{
		IntPtr pString = Marshal::StringToHGlobalAnsi(treePath);

		char* pchString = static_cast<char*>(pString.ToPointer());
		string astring(pchString);

		_tree = (new ChessTree(astring, new FiveWinnerChecker(_trainer->ChessSize)));
	}

	void ChessTrainerWrapper::Run()
	{
		this->OnStart= gcnew SimpleCallback(_trainer, &FiveInRow::ITrainer::Start);
		this->OnEpoch = gcnew SimpleCallback(_trainer, &FiveInRow::ITrainer::OneStep);
		this->OnCheckEnd = gcnew ReturnBoolCallback(_trainer, &FiveInRow::ITrainer::End);

		IntPtr OnStartPtr= Marshal::GetFunctionPointerForDelegate(this->OnStart);
		IntPtr OnEpochPtr = Marshal::GetFunctionPointerForDelegate(this->OnEpoch);
		IntPtr OnCheckEndPtr = Marshal::GetFunctionPointerForDelegate(this->OnCheckEnd);

		_tree->SetCallBacks((SimpleFun*)(void*)OnStartPtr,
			(SimpleFun*)(void*)OnEpochPtr,
			(BoolFun*)(void*)OnCheckEndPtr);
		_tree->StartTraining();
	}

	ChessTree* ChessTrainerWrapper::GetTree()
	{
		return _tree;
	}

}

